import mysql, { Pool, QueryResult } from "mysql2/promise";

const host = process.env.NEXT_DATABASE_HOST;
const user = process.env.NEXT_DATABASE_USER;
const database = process.env.NEXT_DATABASE_NAME;
const password = process.env.NEXT_DATABASE_PWD;

let pool: Pool | undefined = undefined;

try {
  pool = mysql.createPool({
    host,
    user,
    password,
    database,
    waitForConnections: true,
    connectionLimit: 10,
    maxIdle: 10, // 最大空闲连接数，默认等于 `connectionLimit`
    idleTimeout: 60000, // 空闲连接超时，以毫秒为单位，默认值为 60000 ms
    queueLimit: 0,
    enableKeepAlive: true,
    keepAliveInitialDelay: 0,
  });
} catch (e) {
  console.error(e);
}

export const query = async (
  sql: string,
  values?: any[]
): Promise<DatabaseApi.Response> => {
  let message = "",
    data: QueryResult = [],
    success = false;
  if (pool) {
    const connection = await pool.getConnection();
    try {
      const [results] = await connection.query(sql, values);
      success = true;
      data = results;
      connection.release();
    } catch (err) {
      try {
        message = (err as any).toString();
      } catch (e) {
        console.log(e);
        message = "未知错误";
      }
      success = false;
      data = [];
    }
  } else {
    message = "数据库连接失败";
  }
  return { success, message, data };
};
